﻿using System;
using System.Text;
using System.Data;

using LTJ.Common.Generic;
using LTJ.Entity;
using LTJ.Common;
using LTJ.Config;

namespace LTJ.Data.DataProvider
{
    /// <summary>
    /// 用户操作接口
    /// </summary>
    public class Users
    {
        /// <summary>
        /// 创建新用户.
        /// </summary>
        /// <param name="__userinfo">用户信息</param>
        /// <returns>返回用户ID, 如果已存在该用户名则返回-1</returns>
        public static int CreateUser(LTJ.Entity.UserInfo userinfo)
        {
            return DatabaseProvider.GetInstance().CreateUser(userinfo);
        }
        /// <summary>
        /// 获取用户实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static LTJ.Entity.UserInfo GetUserInfo(int id)
        {
            return LoadSingleUserInfo(DatabaseProvider.GetInstance().GetUserInfoByID(id));
        }

        /// <summary>
        /// 根据用户名返回用户id
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>用户id</returns>
        public static LTJ.Entity.UserInfo GetUserInfoByName(string username)
        {
            return LoadSingleUserInfo(DatabaseProvider.GetInstance().GetUserInfoByName(username));
        }

        /// <summary>
        /// 获取用户数量
        /// </summary>
        public static int GetUsersCount(string cons)
        {
            return DatabaseProvider.GetInstance().GetUsersCount(cons);
        }

        /// <summary>
        /// 获取用户分页数据
        /// </summary>
        public static DataTable GetUsersByPage(int pageindex, int pagesize, string condition,string orderstr)
        {
            return DatabaseProvider.GetInstance().GetUsersByPage(pageindex, pagesize, condition, orderstr);
        }

        /// <summary>
        /// 编辑用户.
        /// </summary>
        public static bool UpdateUser(LTJ.Entity.UserInfo userinfo)
        {
            return DatabaseProvider.GetInstance().UpdateUser(userinfo);
        }

        /// <summary>
        /// 检测密码
        /// </summary>
        /// <param name="uid">用户id</param>
        /// <param name="password">密码</param>
        /// <param name="originalpassword">是否非MD5密码</param>
        /// <returns>如果用户密码正确则返回uid, 否则返回-1</returns>
        public static LTJ.Entity.UserInfo CheckPassword(int uid, string password, bool originalpassword)
        {
            IDataReader reader = DatabaseProvider.GetInstance().CheckPassword(uid, password, originalpassword);
            LTJ.Entity.UserInfo userInfo = null;

            if (reader.Read())
            {
                userInfo = new LTJ.Entity.UserInfo();
                userInfo.id = Utils.StrToInt(reader[0].ToString(), -1);
                userInfo.gid = Utils.StrToInt(reader[1].ToString(), -1);
            }
            reader.Close();
            return userInfo;
        }

        /// <summary>
        /// 判断用户密码是否正确
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="originalpassword">是否为未MD5密码</param>
        /// <returns>如果正确则返回uid</returns>
        public static LTJ.Entity.UserInfo CheckPassword(string username, string password, bool originalpassword)
        {
            IDataReader reader = DatabaseProvider.GetInstance().CheckPassword(username, password, originalpassword);
            LTJ.Entity.UserInfo userInfo = null;

            if (reader.Read())
            {
                userInfo = new LTJ.Entity.UserInfo();
                userInfo.id = Utils.StrToInt(reader[0].ToString(), -1);
                userInfo.gid = Utils.StrToInt(reader[1].ToString(), -1);
            }
            reader.Close();
            return userInfo;
        }

        /// <summary>
        /// 去除用户的用户组信息
        /// </summary>
        /// <param name="ids">用户id组合</param>
        /// <param name="gid">用户组id</param>
        /// <returns></returns>
        public static int RemoveUser(string ids,int gid)
        {
            return DatabaseProvider.GetInstance().RemoveUser(ids, gid);
        }

        public static int DelUser(string ids)
        {
            return DatabaseProvider.GetInstance().DelUser(ids);
        }

        /// <summary>
        /// 更新用户状态信息
        /// </summary>
        public static bool UpdateUserStatus(string ids, int status)
        {
            return DatabaseProvider.GetInstance().UpdateUserStatus(ids, status);
        }

        /// <summary>
        /// 更新用户所属管理员ID
        /// </summary>
        /// <param name="uid">用户ID</param>
        /// <param name="fid">管理员ID</param>
        public static bool UpdateUserFid(int uid, int fid)
        {
            return DatabaseProvider.GetInstance().UpdateUserFid(uid, fid);
        }
        /// <summary>
        /// 批量更新用户所属管理员ID
        /// </summary>
        public static bool UpdateUsersFid(int fid, string ids)
        {
            return DatabaseProvider.GetInstance().UpdateUsersFid(fid, ids);
        }
        /// <summary>
        /// 设置企业管理员权限
        /// </summary>
        /// <param name="cid">企业ID</param>
        /// <param name="uid">用户ID</param>
        /// <param name="iscreater">是否超级管理员</param>
        /// <param name="authorities">权限集合</param>
        /// <returns>更新是否成功</returns>
        public static bool SetCorpManagerAuth(int cid, int uid, bool iscreater, string authorities)
        {
            return DatabaseProvider.GetInstance().SetCorpManagerAuth(cid, uid, iscreater, authorities);
        }

        /// <summary>
        /// 获取权限实体
        /// </summary>
        /// <param name="cid">企业ID</param>
        /// <param name="uid">用户ID</param>
        /// <returns>权限实体</returns>
        public static Authority GetAuthInfo(int cid, int uid)
        {
            return LoadSingleAuthority(DatabaseProvider.GetInstance().GetAuthInfo(cid, uid));
        }

        /// <summary>
        /// 获取企业管理员权限
        /// </summary>
        public static DataTable GetCorpManagerAuthList(int pageindex, int pagesize, string condition)
        {
            return DatabaseProvider.GetInstance().GetCorpManagerAuthList(pageindex, pagesize, condition);
        }

        /// <summary>
        /// 根据条件企业管理员数量
        /// </summary>
        public static int GetCorpManagerAuthCount(string condition)
        {
            return DatabaseProvider.GetInstance().GetCorpManagerAuthCount(condition);
        }

        /// <summary>
        /// 批量删除企业管理员
        /// </summary>
        public static void DeleteCorpManagerAuth(string idsparm)
        {
            DatabaseProvider.GetInstance().DeleteCorpManagerAuth(idsparm);
        }

        /// <summary>
        /// 根据用户ID获取用户权限列表
        /// </summary>
        public static List<Authority> GetAuthListByUid(int uid)
        {
            return LoadAuthorityList(DatabaseProvider.GetInstance().GetAuthListByUid(uid));
        }

        #region helper
        public static LTJ.Entity.UserInfo LoadSingleUserInfo(IDataReader reader)
        {
            LTJ.Entity.UserInfo _info = new LTJ.Entity.UserInfo();
            if (reader.Read())
            {
                _info.id = TypeConverter.StrToInt(reader["id"].ToString());
                _info.lname = reader["lname"].ToString();
                _info.rname = reader["rname"].ToString();
                _info.ename = reader["ename"].ToString();
                _info.email = reader["email"].ToString();
                _info.pass = reader["pass"].ToString();
                _info.gid = TypeConverter.ObjectToInt(reader["gid"]);
                _info.cid = TypeConverter.ObjectToInt(reader["cid"]);
                _info.createdate = Utils.GetStandardDateTime(reader["createdate"].ToString());
                _info.lastdate = Utils.GetStandardDateTime(reader["lastdate"].ToString());
                _info.ip = reader["ip"].ToString();
                _info.status = TypeConverter.ObjectToInt(reader["status"], 0);
                _info.authority = reader["authority"].ToString();

                _info.scores = TypeConverter.ObjectToInt(reader["scores"]);
                _info.source = TypeConverter.ObjectToInt(reader["source"]);
                _info.creater = reader["creater"].ToString();
                _info.syspass = reader["syspass"].ToString();
                _info.gender = TypeConverter.StrToBool(reader["gender"].ToString(), false) ? 1 : 0;
                _info.phone = reader["phone"].ToString();
                _info.bio = reader["bio"].ToString();
                _info.olcode = reader["olcode"].ToString();

                if (IsExistField(reader, "ecname")) _info.ecname = reader["ecname"].ToString();
                if (IsExistField(reader, "cname")) _info.cname = reader["cname"].ToString();
            }
            reader.Close();
            return _info;
        }

        public static LTJ.Entity.Authority LoadSingleAuthority(IDataReader reader)
        {
            LTJ.Entity.Authority _info = new Authority();
            if (reader.Read())
            {
                _info.Cid = TypeConverter.ObjectToInt(reader["cid"], 0);
                _info.Uid = TypeConverter.ObjectToInt(reader["uid"], 0);
                _info.Mlevel = TypeConverter.ObjectToInt(reader["mlevel"], 0);
                _info.Ulevel = TypeConverter.ObjectToInt(reader["ulevel"], 0);
                _info.Authoritys = reader["authoritys"].ToString();
            }
            reader.Close();
            return _info;
        }

        public static List<Authority> LoadAuthorityList(IDataReader reader)
        {
            List<Authority> alist = new List<Authority>();

            while (reader.Read())
            {
                Authority authinfo = new Authority();
                authinfo.Cid = TypeConverter.ObjectToInt(reader["cid"], 0);
                authinfo.Uid = TypeConverter.ObjectToInt(reader["uid"], 0);
                authinfo.Mlevel = TypeConverter.ObjectToInt(reader["mlevel"], 0);
                authinfo.Ulevel = TypeConverter.ObjectToInt(reader["ulevel"], 0);
                authinfo.Authoritys = reader["authoritys"].ToString();
                authinfo.Cname = reader["cname"].ToString();
                authinfo.Uname = reader["uname"].ToString();
                alist.Add(authinfo);
            }

            reader.Close();
            return alist;
        }
        #endregion

        /// <summary>
        /// 判定某个字段在IDataReader中是否存在
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public static bool IsExistField(IDataReader reader, string fieldName)
        {
            bool isSuccessfule = false;
            fieldName = fieldName.ToLower();
            int fieldCount = reader.FieldCount;
            for (int i = 0; i < fieldCount; i++)
            {
                string currentFieldName = reader.GetName(i).ToLower();
                if (currentFieldName == fieldName)
                {
                    isSuccessfule = true;
                    break;
                }
            }
            return isSuccessfule;
        }
    }
}
